<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <!-- 双向绑定属性 v-model为复选框的选中状态 -->
          <th><input type="checkbox"  v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <dog
          v-for="(item, index) in goodList"
          :key="index"
          :name="item.name"
          :price="item.price"
          :num="item.num"
          :index="index"
          :checked="item.checked"
          @del="delFn"
          @change="changeFn"
         
         
        />
    
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
//  引入组件对象
import dog from './components/TotalGog.vue'

export default {
  components: { 
 dog },
 
 methods:{
  //删除
  delFn(index){
  this.goodList.splice(index,1)
  },
   // 接收子组件的复选框发生改变的值和索引，改变父组件当前索引的数据
  changeFn(indexa){
    // console.log(index);
 const res= this.goodList.find((item,index)=>index===indexa)
       res.checked = !res.checked;
  }
 },
 //实现全选
  // 计算全选按钮，如果当前父组件里的所有checked属性都为true是勾选
computed:{
 isAll:{
    get() {
        // 判断数组长度，防止数据全部被删除后全选按钮为选中状态
        if (this.goodList.length > 0) {
          return this.goodList.every((item) => item.checked);
        } else {
          return false;
        }
      },
    set(val){
 return this.goodList.forEach((item) => (item.checked = val));
       }
  }
},
  
  data() {
    return {
     
      goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    }
  },
 
}
</script>

<style>

</style>